require "behaviours/attackwall"
require "behaviours/chaseandattack"
require "behaviours/doaction"
require "behaviours/wander"
local BrainCommon = require("brains/braincommon")

local Witch_Gisela_MiniBrain = Class(Brain, function(self, inst)
    Brain._ctor(self, inst)
end)

local FOOD_DISTANCE = 20
local EATFOOD_CANT_TAGS = { "outofreach", "INLIMBO" }
local function EatFoodAction(inst)
    if inst.sg:HasStateTag("busy") then
        return nil
    end

    local food = FindEntity(inst,
        FOOD_DISTANCE,
        function(item)
            return inst.components.eater:CanEat(item) and item:IsOnPassablePoint(true)
        end,
        nil,
        EATFOOD_CANT_TAGS)

    return (food ~= nil and BufferedAction(inst, food, ACTIONS.EAT))
        or nil
end

local TOWNPORTALTALISMAN_DISTANCE = 20
local TOWNPORTALTALISMAN_TAGS = { "townportaltalisman" }
local TOWNPORTALTALISMAN_CANT_TAGS = { "outofreach", "INLIMBO" }
local function GoToTownportaltalisman(inst)
    if inst.sg:HasStateTag("busy") then
        return nil
    end

    local x, y, z = inst.Transform:GetWorldPosition()
    local townportaltalismans = TheSim:FindEntities(x, y, z, TOWNPORTALTALISMAN_DISTANCE, TOWNPORTALTALISMAN_TAGS, TOWNPORTALTALISMAN_CANT_TAGS)
    if #townportaltalismans > 0 then
        return BufferedAction(inst, townportaltalismans[1], ACTIONS.WALKTO)
    end
end

local function GetSpawnPoint(inst)
    return inst.components.knownlocations:GetLocation("spawnpoint")
end

function Witch_Gisela_MiniBrain:OnStart()
    local root = PriorityNode(
    {
        WhileNode(function() return not self.inst.sg:HasStateTag("charge") end, "Not Attacking",
            PriorityNode({
                BrainCommon.PanicTrigger(self.inst),
                DoAction(self.inst, GoToTownportaltalisman, "Find Townportaltalisman"),
                AttackWall(self.inst),
                ChaseAndAttack(self.inst),
                DoAction(self.inst, EatFoodAction, "Find And Eat Food"),
                Wander(self.inst, GetSpawnPoint, 25),
            }, 0.5)
        ),
    }, 0.5)

    self.bt = BT(self.inst, root)
end

function Witch_Gisela_MiniBrain:OnInitializationComplete()
    local pos = self.inst:GetPosition()
    pos.y = 0

    self.inst.components.knownlocations:RememberLocation("spawnpoint", pos, true)
end

return Witch_Gisela_MiniBrain
